import { defineStore } from 'pinia';
import * as Cesium from 'cesium';
import { debounce } from 'lodash';
import { ElMessage } from 'element-plus';
import { createFlightAnimation } from '@/views/Map/InspectionTour/Drone.js';
import RainEffect from '@/views/Map/Weather/rain.js';
import SnowEffect from '@/views/Map/Weather/snow.js';
import FogEffect from '@/views/Map/Weather/fog.js';

export const useMapStore = defineStore('map', {
  state: () => ({
    viewer: null,
    // 无人机相关状态
    drone: {
      entity: null,
      isFlying: false,
      listener: null,
      loading: null
    },
    // 天气效果状态
    weather: {
      rain: { active: false, instance: null },
      snow: { active: false, instance: null },
      fog: { active: false, instance: null }
    },
    // 车辆相关状态
    Car: {
      entity: null,
      isDriver: false,
      listener: null,
      loading: null
    }
  }),

  actions: {
    // 设置Viewer
    setViewer(viewer) {
      this.viewer = viewer; // 保存Viewer实例
    },

    // 无人机飞行控制
    async startDroneFlight(container) {
      if (!this.viewer) {
        ElMessage.error('地图未初始化');
        return;
      }

      if (this.drone.isFlying) {
        ElMessage.warning('无人机已在飞行中');
        return;
      }

      try {
        this.drone.isFlying = true;

        // 局部加载提示
        // this.drone.loading = ElLoading.service({
        //   target: container, // 指定目标容器
        //   lock: true,
        //   text: '无人机巡检启动中...',
        //   background: 'rgba(0, 0, 0, 0.7)'
        // });

        // 创建飞行任务
        this.drone.entity = await createFlightAnimation(
          this.viewer,
          '/model/DJI/DJILine.geojson',
          '/model/DJI/8a0121488c580d1ec30ed08ca241eee4.glb',
          120 // 飞行时间 120s
        );

        // 跟踪无人机
        this.viewer.trackedEntity = this.drone.entity;

        // 设置飞行结束监听
        this.drone.listener = this.viewer.clock.onTick.addEventListener(() => {
          if (Cesium.JulianDate.compare(
            this.viewer.clock.currentTime, // 当前时间
            this.viewer.clock.stopTime  // 飞行结束时间
          ) >= 0) {
            this.stopDroneFlight(true); // 飞行结束
          }
        });

        this.viewer.clock.shouldAnimate = true;

      } catch (error) {
        console.error('飞行失败:', error);
        this.stopDroneFlight(false);
        ElMessage.error(`无人机启动失败: ${error.message}`);
      }
    },

    // 停止无人机飞行
    stopDroneFlight(success = false) {
      // 清理实体
      if (this.drone.entity && this.viewer) {
        this.viewer.entities.remove(this.drone.entity);
      }

      // 移除监听
      if (this.drone.listener) {
        this.viewer.clock.onTick.removeEventListener(this.drone.listener);
      }

      // 重置状态
      this.drone.entity = null;
      this.drone.listener = null;
      this.drone.isFlying = false;

      // 停止动画
      if (this.viewer) {
        this.viewer.trackedEntity = undefined;
        this.viewer.clock.shouldAnimate = false;
      }

      // 关闭加载提示
      if (this.drone.loading) {
        this.drone.loading.close();
        this.drone.loading = null;
      }

      if (success) {
        ElMessage.success('无人机巡检完成');
      }
    },

    // 车辆控制
    async startCar(container) {
      if (!this.viewer) {
        ElMessage.error('地图未初始化');
        return;
      }

      if (this.Car.isDriver) {
        ElMessage.warning('车辆已驾驶中');
        return;
      }

      try {
        this.Car.isDriver = true;

        // 局部加载提示
        this.Car.loading = ElLoading.service({
          target: container, // 指定目标容器
          lock: true,
          text: '车辆驾驶启动中...',
          background: 'rgba(0, 0, 0, 0.7)'
        });

        // 创建飞行任务
        this.Car.entity = await createFlightAnimation(
          this.viewer,
          '/model/Car/gd_Line.geojson',
          '/model/Car/low-poly_cartoon_style_car_01.glb',
          120 // 飞行时间 120s
        );

        // 跟踪车辆
        this.viewer.trackedEntity = this.Car.entity;

        // 设置飞行结束监听
        this.Car.listener = this.viewer.clock.onTick.addEventListener(() => {
          if (Cesium.JulianDate.compare(
            this.viewer.clock.currentTime,
            this.viewer.clock.stopTime
          ) >= 0) {
            this.stopCar(true);
          }
        });

        this.viewer.clock.shouldAnimate = true;

      } catch (error) {
        console.error('驾驶失败:', error);
        this.stopCar(false);
        ElMessage.error(`车辆启动失败: ${error.message}`);
      }
    },

    // 点击查看开车路径
    stopCar(success = false) {
      // 清理实体
      if (this.Car.entity && this.viewer) {
        this.viewer.entities.remove(this.Car.entity);
      }

      // 移除监听
      if (this.Car.listener) {
        this.viewer.clock.onTick.removeEventListener(this.Car.listener);
      }

      // 重置状态
      this.Car.entity = null;
      this.Car.listener = null;
      this.Car.isDriver = false;

      // 停止动画
      if (this.viewer) {
        this.viewer.trackedEntity = undefined;
        this.viewer.clock.shouldAnimate = false;
      }

      // 关闭加载提示
      if (this.Car.loading) {
        this.Car.loading.close();
        this.Car.loading = null;
      }

      if (success) {
        ElMessage.success('车辆驾驶完成');
      }
    },

    // 使用 lodash 的 debounce
    flyTo: debounce(function(position) {
      if (!this.viewer) {
        console.warn('Viewer not initialized');
        return;
      }

      try {
        this.viewer.camera.flyTo({
          destination: Cesium.Cartesian3.fromDegrees(
            position.longitude,
            position.latitude,
            position.height || 2000, // 默认高度 2000m
          ),
          duration: 2,
        });
      } catch (error) {
        console.error('Fly to error:', error);
      }
    }, 300),

    // 天气效果控制
    initWeatherEffects() {
      if (!this.viewer) return;

      this.weather.rain.instance = new RainEffect();
      this.weather.rain.instance.init(this.viewer);
      this.weather.rain.instance.show(this.weather.rain.active);

      this.weather.snow.instance = new SnowEffect();
      this.weather.snow.instance.init(this.viewer);
      this.weather.snow.instance.show(this.weather.snow.active);

      this.weather.fog.instance = new FogEffect();
      this.weather.fog.instance.init(this.viewer);
      this.weather.fog.instance.show(this.weather.fog.active);
    },

    toggleWeatherEffect(type) {
      if (!this.viewer) return;

      // 关闭其他天气效果
      Object.keys(this.weather).forEach(key => {
        if (key !== type) {
          this.weather[key].active = false;
          if (this.weather[key].instance) {
            this.weather[key].instance.show(false);
          }
        }
      });

      // 切换当前天气
      this.weather[type].active = !this.weather[type].active;
      if (this.weather[type].instance) {
        this.weather[type].instance.show(this.weather[type].active);
      }
    },

    clearAllEffects() {
      // 清理天气
      Object.keys(this.weather).forEach(key => {
        this.weather[key].active = false;
        if (this.weather[key].instance) {
          this.weather[key].instance.show(false);
        }
      });

      // 清理实体
      if (this.viewer) {
        this.viewer.entities.removeAll();
      }
    },


    // 清理所有资源
    cleanup() {
      this.stopDroneFlight();
      this.clearAllEffects();
    }
  }
});
